import { base64toBlob } from "./chat"

//验证用户名
export function checkName(val) {
  var patrn = /^(\w){1,20}$/
  if (patrn.exec(val)) {
    return true
  }
  return false
}
//验证密码
export function checkPassword(val) {
  var patrn = /^(\w){6,18}$/
  if (patrn.exec(val)) {
    return true
  }
  return false
}
// 正则校验IP的合法性
export function validateIPAddress(rule, value, callback) {
  let regexp =
    /^((2(5[0-5]|[0-4]\d))|[0-1]?\d{1,2})(\.((2(5[0-5]|[0-4]\d))|[0-1]?\d{1,2})){3}$/
  let isCorrect = true
  if (regexp.test(value) == false) {
    isCorrect = false
  }
  if (value == "") {
    return callback(new Error("请输入iP地址"))
  } else if (!isCorrect) {
    callback(new Error("请输入正确对ip地址"))
  } else {
    callback()
  }
}
// 正则校验手机号码
export function validateMobile(rule, value, callback) {
  console.log(value)
  let regexp =
    /^(13[0-9]|14[01456879]|15[0-3,5-9]|16[2567]|17[0-8]|18[0-9]|19[0-3,5-9])\d{8}$/
  console.log(regexp.test(value))
  let isCorrect = true
  if (regexp.test(value) == false) {
    isCorrect = false
  }
  if (value == "") {
    return callback(new Error("请输入有效的电话号码"))
  } else if (!isCorrect) {
    callback(new Error("请输入有效的电话号码"))
  } else {
    callback()
  }
}

/**
 * 存储localStorage
 */
export function setLocalStorage(name, content) {
  if (!name) return
  if (typeof content !== "string") {
    content = JSON.stringify(content)
  }
  window.localStorage.setItem(name, content)
}

/**
 * 获取localStorage
 */
export function getLocalStorage(name) {
  if (!name) return
  return window.localStorage.getItem(name)
}

/**
 * 删除localStorage
 */
export function removeLocalStorage(name) {
  if (!name) return
  window.localStorage.removeItem(name)
}
/**
 * 存储SessionStorage
 */
export function setSessionStorage(name, content) {
  if (!name) return
  if (typeof content !== "string") {
    content = JSON.stringify(content)
  }
  window.sessionStorage.setItem(name, content)
}

/**
 * 获取SessionStorage
 */
export function getSessionStorage(name) {
  if (!name) return
  return window.sessionStorage.getItem(name)
}
/**
 * 删除SessionStorage
 */
export function removeSessionStorage(name) {
  if (!name) return
  window.sessionStorage.removeItem(name)
}
/**
 * 存储Cookie
 */
export function setCookie(name, content) {
  if (!name) return
  if (typeof content !== "string") {
    content = JSON.stringify(content)
  }
  var Days = 30
  var exp = new Date()
  exp.setTime(exp.getTime() + Days * 24 * 60 * 60 * 1000)
  window.document.cookie =
    name + "=" + escape(content) + ";expires=" + exp.toGMTString()
}

/**
 * 获取Cookie
 */
export function getCookie(name) {
  var arr,
    reg = new RegExp("(^| )" + name + "=([^;]*)(;|$)")

  if ((arr = document.cookie.match(reg))) {
    // console.log(unescape(arr[2]));
    return unescape(arr[2])
  } else {
    return null
  }
}
/**
 * 删除Cookie
 */
export function removeCookie(name) {
  var exp = new Date()
  exp.setTime(exp.getTime() - 1)
  var cval = getCookie(name)
  if (cval != null) {
    window.document.cookie = name + "=" + cval + ";expires=" + exp.toGMTString()
  }
}

/**
 * 判断是否图片，格式为 .PNG，.JPEG, .JPG, .BMP
 */
export function isPhoto(file) {
  let res = false
  let arr
  let extention
  if (file.name.includes(".")) {
    arr = file.name.split(".")
    extention = arr[arr.length - 1].toUpperCase()
    if (extention.match(/PNG|JPEG|JPG|BMP/)) {
      res = true
    }
  }
  return res
}

/**
 * 元素相对于body的offsetTop
 */
export function getOffsetTopByBody(el) {
  let otop = 0
  while (el) {
    otop += el.offsetTop
    el = el.offsetParent
  }
  return otop
}

export function getPath(path) {
  let rep = path || window.location.href
  let index = rep.indexOf("#") + 1
  if (rep.includes("#")) {
    rep = rep.substring(index)
  }
  return rep
}

export function deepClone(obj) {
  // 对象或者数组深拷贝
  let rev = ""
  try {
    rev = JSON.parse(JSON.stringify(obj))
  } catch (e) {
    console.log(e)
  }
  return rev
}
/**
 * 获取年月日
 *
 * @param {String} dateStr 时间毫秒数
 * @returns 格式化后的时间
 */
export function getYearMonthDay(dateStr) {
  if (!dateStr) return ""
  return formatDate(dateStr, "yyyy-MM-dd")
}

/**
 * 获取年月日 时分秒
 *
 * @param {String} dateStr 时间毫秒数
 * @returns 格式化后的时间
 */
export function getDate(dateStr, formateStr = "yyyy-MM-dd HH:mm:ss") {
  if (!dateStr) return ""
  return formatDate(dateStr, formateStr)
}

/**
 * 格式化时间
 *
 * @param {String} dateStr 时间毫秒数
 * @returns 格式化后的时间
 */
export function formatDate(dateStr, format) {
  if (!dateStr) return ""
  var date = new Date(parseInt(dateStr))
  return date.pattern(format)
}

/** * 对Date的扩展，将 Date 转化为指定格式的String * 月(M)、日(d)、12小时(h)、24小时(H)、分(m)、秒(s)、周(E)、季度(q)
 可以用 1-2 个占位符 * 年(y)可以用 1-4 个占位符，毫秒(S)只能用 1 个占位符(是 1-3 位的数字) 
 * eg: 
 * (new Date()).pattern('yyyy-MM-dd hh:mm:ss.S')==> 2006-07-02 08:09:04.423
 * (new Date()).pattern('yyyy-MM-dd E HH:mm:ss') ==> 2009-03-10 二 20:09:04
 * (new Date()).pattern('yyyy-MM-dd EE hh:mm:ss') ==> 2009-03-10 周二 08:09:04
 * (new Date()).pattern('yyyy-MM-dd EEE hh:mm:ss') ==> 2009-03-10 星期二 08:09:04
 * (new Date()).pattern('yyyy-M-d h:m:s.S') ==> 2006-7-2 8:9:4.18
 */
Date.prototype.pattern = function (fmt) {
  var o = {
    "M+": this.getMonth() + 1, // 月份
    "d+": this.getDate(), // 日
    "h+": this.getHours() % 12 === 0 ? 12 : this.getHours() % 12, // 小时
    "H+": this.getHours(), // 小时
    "m+": this.getMinutes(), // 分
    "s+": this.getSeconds(), // 秒
    "q+": Math.floor((this.getMonth() + 3) / 3), // 季度
    S: this.getMilliseconds() // 毫秒
  }
  var week = {
    0: "\u65e5",
    1: "\u4e00",
    2: "\u4e8c",
    3: "\u4e09",
    4: "\u56db",
    5: "\u4e94",
    6: "\u516d"
  }
  if (/(y+)/.test(fmt)) {
    fmt = fmt.replace(
      RegExp.$1,
      (this.getFullYear() + "").substr(4 - RegExp.$1.length)
    )
  }
  if (/(E+)/.test(fmt)) {
    fmt = fmt.replace(
      RegExp.$1,
      (RegExp.$1.length > 1
        ? RegExp.$1.length > 2
          ? "\u661f\u671f"
          : "\u5468"
        : "") + week[this.getDay() + ""]
    )
  }
  for (var k in o) {
    if (new RegExp("(" + k + ")").test(fmt)) {
      fmt = fmt.replace(
        RegExp.$1,
        RegExp.$1.length === 1 ? o[k] : ("00" + o[k]).substr(("" + o[k]).length)
      )
    }
  }
  return fmt
}

/* author: xu 20190505
 * effect: translate Object that whick key has Capitalization to underline and accordingly lower letter.
 * example:
 * import oe from "@/assets/js/plugin/objectExtention"; //功能
 * let arr0 = oe.camelToUnderline({
 *	ABC:123
 * });
 * let arr1 = oe.underlineToCamel({
 *	_a_b_ee:123
 * });
 * let arr2 = {
 * 	ABC:100
 * }
 * arr2 = oe.itemCamelToUnderline(arr2)
 * let arr3 = [{
 * 	ABC:100
 * },{
 * 	DF: 200
 * }]
 * arr3 = oe.itemCamelToUnderline(arr3)
 * let arr4 = [{
 * 	A_bcccC:100
 * },{
 * 	DF_cc: 200
 * }]
 * arr4 = oe.itemUnderlineToCamel(arr4)
 */
export function camelToUnderline(obj) {
  // 驼峰命名的属性转换为“_”加上对应的小写
  let res = {}
  for (let [key, value] of Object.entries(obj)) {
    let match = key.match(/[A-Z]{1}/g),
      tmpkey = key
    if (match) {
      match.forEach((item) => {
        tmpkey = tmpkey.replace(item, "_" + item.toLowerCase())
      })
    }
    res[tmpkey] = value
  }
  return res
}
export function underlineToCamel(obj) {
  // “_”加上对应的小写的属性转换为驼峰命名
  let res = {}
  for (let [key, value] of Object.entries(obj)) {
    let match = key.match(/_[a-z]{1}/g),
      tmpkey = key
    if (match) {
      match.forEach((item) => {
        tmpkey = tmpkey.replace(item, item.toUpperCase().substring(1))
      })
    }
    res[tmpkey] = value
  }
  return res
}
export function itemCamelToUnderline(param) {
  // param 可能是对象，也可能是数组
  // 若是数组，处理数组元素的属性，驼峰命名的属性转换为“_”加上对应的小写
  let res = {}
  if (param instanceof Array) {
    res = []
    if (param && param.length) {
      param.forEach((item, index) => {
        res[index] = this.camelToUnderline(item)
      })
    }
  } else {
    res = this.camelToUnderline(param)
  }
  return res
}
export function itemUnderlineToCamel(param) {
  // param 可能是对象，也可能是数组
  // 若是数组，处理数组元素的属性，“_”加上对应的小写的属性转换为驼峰命名
  let res = {}
  if (param instanceof Array) {
    res = []
    if (param && param.length) {
      param.forEach((item, index) => {
        res[index] = this.underlineToCamel(item)
      })
    }
  } else {
    res = this.camelToUnderline(param)
  }
  return res
}
export function $confirm(param) {
  this.$confirm(
    '<div class="dialog-text text-center"><i class="icon iconfont icontishi"></i>' +
      param.message +
      "</div>",
    param.title || "提示",
    {
      customClass: "model-dialog dialog-tips width60",
      dangerouslyUseHTMLString: true,
      cancelButtonClass:
        "el-button el-button--primary el-button--mini is-plain",
      confirmButtonClass: "el-button el-button--primary el-button--mini"
    }
  )
    .then(() => {
      if (param.success) {
        param.success()
      }
    })
    .catch(() => {
      if (param.error) {
        param.error()
      }
    })
}
// how to use $confirm
// this.tools.$confirm.call(this, {
//   message: '确定要将所选模型注销，注销后模型将不能被调用。',
//   success: function(){
//   }
// });
export function modelState(i) {
  // 模型状态(0创建,1提交,2未通过,3发布,4注销
  let index = i ? i : 0
  return ["创建", "提交", "未通过", "发布", "注销"][index]
}

/**
 * @description 下载文件方法
 * @param {Blob} blob 文件流
 * @param {String} fileName 文件名称
 */
export function downloadFile(blob, fileName) {
  if ("download" in document.createElement("a")) {
    const elink = document.createElement("a")
    elink.href = URL.createObjectURL(blob)
    elink.download = fileName
    elink.style.display = "none"
    document.body.appendChild(elink)
    elink.click()
    URL.revokeObjectURL(elink.href)
    document.body.removeChild(elink)
  } else {
    navigator.msSaveBlob(blob, fileName)
  }
}

export function downloadFileByLink(url, fileName) {
  // window.open(url)
  const elink = document.createElement("a")

  elink.download = fileName
  elink.href = new URL(url)
  elink.style.display = "none"
  document.body.appendChild(elink)
  elink.click()
  URL.revokeObjectURL(elink.href)
  document.body.removeChild(elink)
}

export function addDomain(content) {
  // eslint-disable-next-line no-undef
  return content.replace("[image]", minioEndpoint_mini)
}

/**
 * @description 移除html富文本中所有标签
 * @param {*} htmlString html富文本
 */
export function removeHTMLTags(htmlString) {
  const parser = new DOMParser()
  const dom = parser.parseFromString(htmlString, "text/html")
  return dom.body.textContent
}

/**
 * @description 将arraybuffer转换成base64
 * @param {*} buffer
 * @returns
 */
export function arrayBufferToBase64(buffer) {
  let binary = ""
  let bytes = new Uint8Array(buffer)
  for (let len = bytes.byteLength, i = 0; i < len; i++) {
    binary += String.fromCharCode(bytes[i])
  }
  return window.btoa(binary)
}

export function timeFormate(time) {
  function add0(m) {
    return m < 10 ? "0" + m : m
  }

  var d = new Date(time)
  var y = d.getFullYear() + "-"
  var m =
    d.getMonth() + 1 < 10
      ? "0" + (d.getMonth() + 1) + "-"
      : d.getMonth() + 1 + "-"
  var dd = d.getDate() < 10 ? "0" + d.getDate() : d.getDate()
  var h = d.getHours()
  var mm = d.getMinutes()
  var s = d.getSeconds()
  var date = y + m + dd + " " + add0(h) + ":" + add0(mm) + ":" + add0(s)
  return date
}

export function isURL(str) {
  // 匹配URL的正则表达式
  var pattern = new RegExp(
    "^(https?:\\/\\/)?" + // 协议
      "((([a-z\\d]([a-z\\d-]*[a-z\\d])*)\\.)+[a-z]{2,}|" + // 域名
      "((\\d{1,3}\\.){3}\\d{1,3}))" + // 或者IP地址
      "(\\:\\d+)?(\\/[-a-z\\d%_.~+]*)*" + // 端口和路径
      "(\\?[;&a-z\\d%_.~+=-]*)?" + // 查询字符串
      "(\\#[-a-z\\d_]*)?$",
    "i"
  ) // 锚点

  return pattern.test(str)
}

//生成请求唯一标识（用于幂等和缓存）
export function generateReqKey(config) {
  const { url, method, data, params } = config
  return `${url}_${method}_${JSON.stringify(data)}_${JSON.stringify(params)}`
}

//比较两个数组对象是否相等
export function compareArray(arr1, arr2) {
  if (arr1.length !== arr2.length) return false
  for (let i = 0; i < arr1.length; i++) {
    const item1 = arr1[i]
    const item2 = arr2[i]
    // 比较对象属性是否相等
    for (const key in item1) {
      if (item1[key] !== item2[key]) {
        return false
      }
    }
  }
  return true
}
